package com.hefan.livingQueue.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.util.DynamicProperties;
import com.hefan.live.itf.LivingRedisOptService;
import com.hefan.livingQueue.bean.LivingVo;
import com.hefan.livingQueue.itf.PoolOptService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by kevin_zhang on 11/28/16.
 */
@Component("poolOptService")
public class PoolOptServiceImpl implements PoolOptService {
    public Logger logger = LoggerFactory.getLogger(PoolOptServiceImpl.class);

    @Resource
    JedisService jedisService;

    @Reference
    LivingRedisOptService livingRedisOptService;

    /**
     * 排队结束，进入准入池
     *
     * @param listKey 排队池元素
     * @param hashKey 准入池元素
     * @param count   每次迁移个数
     */
    @Override
    public void waitToEnter(String listKey, String hashKey, int count) {
        for (int i = 0; i < count; i++) {
            Object finshObj = null;
            String userId = "";
            try {
                //从排队池中取元素，结束等待
                finshObj = jedisService.lpop(listKey);
                if (null != finshObj) {
                    userId = (String) finshObj;
                }
                if (StringUtils.isNotBlank(userId)) {
                    jedisService.hset(hashKey, userId, userId, GlobalConstants.LIVING_PREPARE_QUEUE_CACHE_TIME);
                } else continue;
            } catch (Exception e) {
                logger.info("排队结束任务异常");
                e.printStackTrace();
            }
        }
    }


    /**
     * 用户进入直播间排队处理
     */
    @Override
    public ResultBean enterQueueOperate(LivingVo item) {
        ResultBean resultBean = new ResultBean();
        resultBean.setCode(ResultCode.SUCCESS.get_code());

        long waitQueuelimitMinNum = DynamicProperties.getLong("living_wait_queue_min_person_num_limit");
        long waitQueuelimitMidNum = DynamicProperties.getLong("living_wait_queue_mid_person_num_limit");
        long waitQueuelimitMaxNum = DynamicProperties.getLong("living_wait_queue_max_person_num_limit");
        logger.info("直播间进入等待队列  -waitQueuelimitMinNum：" + waitQueuelimitMinNum);
        logger.info("直播间进入等待队列  -waitQueuelimitMidNum：" + waitQueuelimitMidNum);
        logger.info("直播间进入等待队列  -waitQueuelimitMaxNum：" + waitQueuelimitMaxNum);

        long watchNum = Long.parseLong(livingRedisOptService.getLivingWatchNum(item.getLiveUuid()));
        logger.info("直播间进入等待队列  -watchNum：" + watchNum);

        if (watchNum <= waitQueuelimitMinNum) {
            logger.info("直播间进入等待队列  -不满足进入等待队列");
            return resultBean;
        } else {
            try {
                //明星/片场走绿色通道
                if (item.getUserType() == 2 || item.getUserType() == 3) {
                    if (jedisService.hexists(GlobalConstants.LIVING_VIP_PREPARE_QUEUE_KEY + item.getLiveUuid(), item.getUserId())) {
                        //绿色通道已存在该用户，允许进入
                        jedisService.hdel(GlobalConstants.LIVING_VIP_PREPARE_QUEUE_KEY + item.getLiveUuid(), item.getUserId());
                        return resultBean;
                    }
                    //加入绿色通道
                    jedisService.hset(GlobalConstants.LIVING_VIP_PREPARE_QUEUE_KEY + item.getLiveUuid(), item.getUserId(), item.getUserId());
                    resultBean.setCode(ResultCode.LivingWaitQueue.get_code());
                    resultBean.setMsg(ResultCode.LivingWaitQueue.getMsg());
                } else {
                    //正常排队通道
                    if (jedisService.hexists(GlobalConstants.LIVING_PREPARE_QUEUE_KEY + item.getLiveUuid(), item.getUserId())) {
                        //正常排队通道存在该用户，允许进入
                        jedisService.hdel(GlobalConstants.LIVING_PREPARE_QUEUE_KEY + item.getLiveUuid(), item.getUserId());
                        return resultBean;
                    }
                    resultBean.setCode(ResultCode.LivingWaitQueue.get_code());
                    resultBean.setMsg(ResultCode.LivingWaitQueue.getMsg());
                    //加入正常排队通道
                    jedisService.rpush(GlobalConstants.LIVING_PREPARE_QUEUE_KEY + item.getLiveUuid(), item.getUserId());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("进入直播间排队处理 -失败");
                return resultBean;
            }
        }
        return resultBean;
    }
}
